package myview;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;

import com.bigchun.woodhunter.R;
import com.bigchun.woodhunter.databinding.DialogInputCustomBinding;

import util.SoftKeyBoardUtil;

public class InputCustomDialog extends Dialog {
    public InputCustomDialog(@NonNull Context context) {
        super(context, R.style.Dialog);
    }

    InputListener listener;

    @Override
    public void onContentChanged() {
        super.onContentChanged();
        Window window = getWindow();
        if (window != null) {
            window.setLayout(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            window.setBackgroundDrawable(null);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DialogInputCustomBinding vb = DialogInputCustomBinding.inflate(getLayoutInflater(), (ViewGroup) getWindow().getDecorView(), false);
        setContentView(vb.getRoot());
        vb.cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SoftKeyBoardUtil.hideKeyBoard(getContext(), vb.et.getWindowToken());
                dismiss();
            }
        });
        vb.confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = vb.et.getText().toString();
                if (TextUtils.isEmpty(text)) {
                    return;
                }
                SoftKeyBoardUtil.hideKeyBoard(getContext(), vb.et.getWindowToken());
                if (listener != null) {
                    listener.input(vb.et.getText().toString());
                }
                dismiss();
            }
        });
        vb.getRoot().postDelayed(new Runnable() {
            @Override
            public void run() {
                vb.et.requestFocus();
                SoftKeyBoardUtil.showKeyBoard(getContext(), getWindow());
            }
        }, 20);
    }

    public InputListener getListener() {
        return listener;
    }

    public void setListener(InputListener listener) {
        this.listener = listener;
    }

    public interface InputListener {
        void input(String str);
    }
}
